package com.angel.web.health;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.angel.core.util.JsonUtil;
import com.github.pagehelper.StringUtil;

/**
 * @author hanlinxiu
 * 
 *         文件上传
 *
 */
@Controller
@RequestMapping("/downloadFile")
public class DownLoadController {

	private static final Logger logger = LoggerFactory.getLogger(DownLoadController.class);

	/**
	 * 单个文件下载
	 * 
	 * @param fileName
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/download")
	public ResponseEntity download(String fileName, String filePath) throws IOException {

		URL url = new URL(filePath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		// 设置超时间为10秒
		conn.setConnectTimeout(10 * 1000);

		// 得到输入流
		InputStream inputStream = conn.getInputStream();

		String ext = filePath.substring(filePath.lastIndexOf("."));

		// 获取自己数组
		byte[] getData = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		while ((len = inputStream.read(getData)) != -1) {
			bos.write(getData, 0, len);
		}

		bos.close();
		getData = bos.toByteArray();
		
		fileName = new String(fileName.getBytes("gb2312"), "iso8859-1") + "." + ext; 
		
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", fileName);

		return new ResponseEntity(getData, headers, HttpStatus.CREATED);
	}

	/**
	 * 文件批量下载
	 * 
	 * @param fileName
	 * @param filePath
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	@RequestMapping("/downloadFiles")
	public ResponseEntity downloadFiles(String myFiles, String zipName) throws IOException {
		
		String[] fileArray = myFiles.split(",,");
		
		File[] packFiles = new File[fileArray.length];

			for (int i = 0; i <= fileArray.length-1; i++) {
				try {
				
				Map<String, String> fileMap = JsonUtil.jsonStringToMap(fileArray[i]);
				
				String fileName = (String) fileMap.get("name");
				String filePath = (String) fileMap.get("url");
				
				String ext = filePath.substring(filePath.lastIndexOf("."));

				URL url = new URL(filePath);
				
				//读取url到file
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				// 设置超时间为10秒
				conn.setConnectTimeout(10 * 1000);

				// 得到输入流
				InputStream inputStream = conn.getInputStream();

				// 获取自己数组
				byte[] getData = new byte[1024];
				int len = 0;
				ByteArrayOutputStream bos = new ByteArrayOutputStream();

				while ((len = inputStream.read(getData)) != -1) {
					bos.write(getData, 0, len);
				}

				bos.close();
				getData = bos.toByteArray();
			
				File file = createTempFile(fileName, ext);
				if(!file.exists() || file == null){
					continue;
				}
				
			    OutputStream output = new FileOutputStream(file);
			    BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
			    
			    bufferedOutput.write(getData);
				
				packFiles[i] = file;
				
				bufferedOutput.close();
				
				} catch (Exception e) {
					logger.error("生成file数组", e.getMessage());
					continue;
				}
			}
		
		File zipFile = toZip(packFiles, zipName);
		
		//String zipName = "体检报告.zip";
		
		String dfileName = new String(zipName.getBytes("gb2312"), "iso8859-1") + ".zip"; 
		HttpHeaders headers = new HttpHeaders(); 
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
		headers.setContentDispositionFormData("attachment", dfileName); 
		
		return new ResponseEntity(FileUtils.readFileToByteArray(zipFile), headers, HttpStatus.CREATED);
	}
	
    /**
     * 将附件和稿件信息打成ZIP包
     * @param file 附件文件
     * @param fileStr cnml文件内容
     * @param zipName  zip名称
     * @throws IOException 
     * @return File
     */
	public File toZip(File[] file, String zipName) throws IOException {
		File tempFile = null;
		
			byte data[] = new byte[1024];
			BufferedInputStream origin = null;
			tempFile = createTempFile(zipName, ".zip");
			// logger.info(tempFile.getAbsolutePath());
			logger.info("tempFile:" + tempFile);
			ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempFile));
			/** 附件情况处理 */
			if (file != null) {
				for (int i = 0; i < file.length; i++) {
					try {
					File f = file[i];
					FileInputStream fi = new FileInputStream(f);
					origin = new BufferedInputStream(fi, 1024);
					String temp = f.getAbsolutePath();
					//String fname = websharp.util.FileTools.extractFileName(temp);
					String fname = f.getName();
					ZipEntry entry = new ZipEntry(fname);
					zos.putNextEntry(entry);
					int count;
					while ((count = origin.read(data)) != -1) {
						zos.write(data, 0, count);
					}
					zos.closeEntry();

					origin.close();
					} catch (Exception e) {
						logger.error("将附件和稿件信息打成ZIP包", e.getMessage());
						continue;
					}
				}
					
			}
			
		
		return tempFile;
	}

	/**
	 * 
	 * Function : createTempFile
	 * 
	 * @param prefix
	 *            后缀
	 * @param ext
	 *            后缀
	 * @throws IOException
	 *             异常
	 * @return : File 返回类型
	 *
	 */
	private File createTempFile(String prefix, String ext) throws IOException {
		File dateFile;
		try {
			String dateFilePath = "c:/" + new SimpleDateFormat("yyyy/MMdd").format(new Date());
			dateFile = new File(dateFilePath);
			dateFile.mkdirs();
		} catch (Exception e) {
			logger.error("", e.getMessage());
			throw new IOException("创建temp失败", e);
		}
		return File.createTempFile(prefix + "-", ext, dateFile);

	}

}